package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.anno.Cachedable;
import com.qk.vo.portal.OverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/17 16:57
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class ReportAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("@annotation(com.qk.common.anno.Cachedable)")
    public Object around(ProceedingJoinPoint pjp){
        Object result;
        String cacheKey = null;
        long expireTime = 0;
        TimeUnit expireTimeUnit = null;
        try {
            Class<?> aClass = pjp.getTarget().getClass();
            String name = pjp.getSignature().getName();
            Cachedable cachedable = aClass.getMethod(name).getAnnotation(Cachedable.class);
            cacheKey = cachedable.redispreKey() + name;
            expireTime = cachedable.expireTime();
            expireTimeUnit = cachedable.expireTimeUnit();
            String cacheValue = redisTemplate.opsForValue().get(cacheKey);
            if (ObjectUtil.isNotEmpty(cacheValue)) {
                return JSONUtil.toBean(cacheValue, OverviewVO.class);
            }
        } catch (Exception e) {
            log.error("获取总览数据缓存失败", e);
        }
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            result = Result.error("操作失败,请重试");
        }
        try {
            redisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(result), expireTime, expireTimeUnit);
        } catch (Exception e) {
            log.error("设置总览数据缓存失败", e);
        }
        return result;
    }
}
